package com.example.firstprojectnew.service;

import com.example.firstprojectnew.common.WrapMapper;
import com.example.firstprojectnew.common.Wrapper;
import com.example.firstprojectnew.entity.Course;
import com.example.firstprojectnew.entity.Selection;
import com.example.firstprojectnew.entity.User;
import com.example.firstprojectnew.mapper.CourseMapper;
import com.example.firstprojectnew.mapper.SelectionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @Author: lihua
 * @Date: 2025/4/3 14:15
 * @Version: v1.0.0
 * @Description:
 **/

@Service
public class CourseService {

    @Autowired
    private CourseMapper courseMapper;

    @Autowired
    private SelectionMapper selectionMapper;

    public Course getCourseById(String courseId){
        return courseMapper.getCourseById(courseId);
    }

    public Wrapper select(User user, Course course){
        if(course.getStuCount() >= course.getCapacity()){
            return WrapMapper.error("课程人数已满");
        }
        int stuCourseCount = selectionMapper.getStudentCourseCount(user.getUserId());
        if(stuCourseCount >= 3){
            return WrapMapper.error("学生已选3门课程");
        }
        Selection selection = selectionMapper.getSelectionByStuIdAndCID(user.getUserId(),course.getCourseId());
        if(selection != null){
            return WrapMapper.error("学生已选过此课程");
        }
        selection = new Selection();
        selection.setCourseId(course.getCourseId());
        selection.setStudentId(user.getUserId());
        selection.setStatus(1);
        selection.setCreateTime(new Date());
        selectionMapper.insert(selection);
        course.setStuCount(course.getStuCount() + 1);
        courseMapper.update(course);
        return WrapMapper.ok("选课成功!");
    }

}
